<template>
  <div class="box">
   <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="addInfo"/>
    <!-- 中间表格模块 -->
    <!-- 缆桩弹出 -->

    <div v-if="exl">
      <el-drawer
        :before-close="handleCloseBefore1"
        :with-header="true"
        :title="'缆桩列表'"
        :visible.sync="exl"
        :modal-append-to-body="false"
        size="55%"
      >
        <bittInfoList :menuArr="menuArr" :senData="nowData" :queryInfo="queryInfo" :P_berthNo="P_berthNo" :tableHeight="tableHeight"></bittInfoList>
      </el-drawer>
    </div>

    <!-- 泊位数据列表 -->

    <BaseTable
      :data="cargotableData"
      :columns="cargotableDataColumns"
      :tableHeight="tableHeight"
      :pagination="false"
      :loading="loading"
    ></BaseTable>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryall.startpage"
        :page-sizes="[10, 15, 20, 25, 30]"
        :page-size="queryall.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
      ></el-pagination>

      <!-- 新增泊位信息的弹出框 -->
      <el-drawer
        :title="flag ? '新增泊位信息' : '编辑泊位信息'"
        :visible.sync="addDialogVisible"
        width="50%"
        :before-close="handleCloseBefore"
      >
        <!-- 新增人员的form表单 -->
        <el-form size="small" ref="addForm" :model="addForm" :rules="addFormRule" style="padding:10px 20px" >
            <el-form-item label="泊位编号" prop="berthNo" label-width="120px">
              <el-input
                @input="
                  addForm.berthNo = verifyfilter('chareBO', addForm.berthNo)
                "
                v-model="addForm.berthNo"
              ></el-input>
            </el-form-item>
            <el-form-item label="主泊位" prop="berthNoMain" label-width="120px">
              <el-input
                  @input="
                  addForm.berthNoMain = verifyfilter('chareBO', addForm.berthNoMain)
                "
                  v-model="addForm.berthNoMain"
              ></el-input>
            </el-form-item>
            <el-form-item label="泊位长度" prop="berthLength" label-width="120px">
              <el-input
                  @input="
                  addForm.berthLength = verifyfilter(
                    'digit',
                    addForm.berthLength
                  )
                "
                  v-model="addForm.berthLength"
              ></el-input>
            </el-form-item>
            <el-form-item label="泊位水深" prop="berthDeepth" label-width="120px">
              <el-input
                  @input="
                  addForm.berthDeepth = setThree(addForm.berthDeepth)
                "
                  v-model="addForm.berthDeepth"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属公司" prop="companyId" label-width="120px">
              <el-select
                  @change="selectCompId"
                  clearable
                  v-model="addForm.companyId"
                  placeholder="所属公司"
                  style="width:100%"
              >
                <el-option
                    v-for="(item, index) in selectCompany"
                    :key="index"
                    :label="item.companyName"
                    :value="item.companyId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属区域" label-width="120px">
              <el-select
                  @change="selectRegionCode"
                  clearable
                  v-model="addForm.regionCode"
                  placeholder="所属区域"
                  style="width:100%"
              >
                <el-option
                    v-for="(item, index) in regionOption"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="左泊位" label-width="120px">
              <el-select
                  placeholder="请选择左泊位"
                  clearable
                  v-model="addForm.berthNoLeft"
                  style="width:100%"
              >
                <el-option
                    v-for="(item,index) in preBerthIdList"
                    :key="index"
                    :label="item.berthNo"
                    :value="item.berthNo"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="右泊位" label-width="120px">
              <el-select
                  placeholder="请选择右泊位"
                  clearable
                  v-model="addForm.berthNoRight"
                  style="width:100%"
              >
                <el-option
                    v-for="(item,index) in preBerthIdList"
                    :key="index"
                    :label="item.berthNo"
                    :value="item.berthNo"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否主泊位" prop="isMain" label-width="120px">
              <el-select
                  placeholder=""
                  v-model="addForm.isMain"
                  style="width:100%"
              >
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序号" prop="sortNum" label-width="120px">
              <el-input v-model="addForm.sortNum"></el-input>
            </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <!-- 确认 -->
          <el-button size="small" type="primary" @click="addBerth" :loading="berthLoading">{{ berthLoading ? '提交中 ...' : '保 存' }}</el-button>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import bittInfoList from './metabittInfoList.vue'
import BaseTable from '@/components/BaseTable'
import { isObjectValueEqual } from '@/libs/date'
import headerSearch from './component/headerSearch'
import api from '@/api/Basic/metadataBerth'
import publicapi from '@/api/public'
export default {
  name: 'metadataBerth',
  components: { bittInfoList, BaseTable, headerSearch },
  data() {
    return {
      regionOption: [],
      menuFlag: false,
      menuArr: [],
      preBerthIdList: [],
      preBerthIdListMain: [],
      berthLoading: false,
      // 搜索框显示对象
      selectObject: [
        {
          name: '泊位编号',
          type: 'inputVerify',
          verifyTpye: 'char',
          modelName: 'berthNo'

        },
        {
          name: '所属公司',
          type: 'select',
          modelName: 'companyId',
          selectData: this.selectCompany
        }
      ],
      loading: false,
      cargotableDataColumns: [
        { prop: 'berthNo', label: '泊位编号' },
        { prop: 'berthNoMain', label: '主泊位编号' },
        { prop: 'berthLength', label: '泊位长度' },
        { prop: 'berthDeepth', label: '泊位水深' },
        { prop: 'companyName', label: '所属公司' },
        { prop: 'regionName', label: '所属区域' },
        { prop: 'berthNoLeft', label: '左泊位' },
        { prop: 'berthNoRight', label: '右泊位' },
        /* { prop: 'sortNum', label: '排序号' },
        { prop: 'isMain', label: '是否主泊位' },*/
        { prop: 'createName', label: '创建人' },
        { prop: 'createdTime', label: '创建时间' },
        {
          label: '操作',
          align: 'center',
          fixed: 'right',
          width: 200,
          render: (h, params) => {
            return h(
              'div',
              {
                class: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('泊位编辑') ? 'block' : 'none'}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEdit(params.$index, params.row)
                    }
                  }
                }),
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    innerHTML: `<span style='color:#0B6CD6;display: ${this.menuArr.includes('泊位删除') ? 'block' : 'none'}'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.del(params.$index, params.row)
                    }
                  }
                }),
                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  domProps: {
                    // innerHTML: `<span style='color:#67C23A'><i class='iconfont icon-liebiaotubiao_liebiao'></i><span  style='padding-left:5px;'>缆桩列表</span></span>`
                    /* innerHTML: `<span style='color:#9420A8;display: ${this.menuArr.includes('缆桩查询')?"block":"none"}''><i class='iconfont icon-1-09'></i><span  style='padding-left:5px;'>缆桩列表</span></span>`*/
                    innerHTML: `<span style='color:#9420A8;display: ${this.menuArr.includes('缆桩查询') ? 'block' : 'none'}'><i class='iconfont icon-1-09'></i><span  style='padding-left:5px;'>缆桩</span></span>`
                  },
                  on: {
                    click: () => {
                      this.excelFun(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      cargotableData: [],
      queryInfo: {
        bollardNo: ''
      },
      compId: '',
      // 查询表单
      form: {
        berthNo: '',
        companyId: ''
      },
      berthLevels: [], // 设计船型集合取字典值
      berthNatures: [], // 泊位性质集合取字典值
      tableData: [],
      // 查询
      queryall: {
        startpage: 1,
        pagesize: 15
      },
      workAreaList: [],
      exl: false, // 缆桩表格弹出
      // 分页
      totalNum: 1,
      // 当前页码
      currentPage: 2,
      // 对话框隐藏
      addDialogVisible: false,

      // 通过flag控制进行添加操作还是修改操作,为true的时候进行的是添加操作
      flag: true,
      nowData: {},

      selectCompany: [],
      // 新增泊位
      addForm: {
        id: '',
        berthNo: '',
        berthNoMain: '',
        berthLength: '',
        berthDeepth: '',
        companyId: '',
        companyName: '',
        berthNoLeft: '',
        berthNoRight: '',
        isMain: 'Y',
        sortNum: '',
        delFlag: '0',
        regionCode: '',
        regionName: ''
      },
      P_berthNo: '',
      berthUse: [],
      flagHint: false,
      // form表单校验
      addFormRule: {
        berthNo: [
          {
            required: true,
            message: '请输入泊位编号',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 15,
            message: '长度在 1 到 15 个字符',
            trigger: 'blur'
          }
        ],
        berthNoMain: [
          {
            required: true,
            message: '请输入主泊位编号',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 15,
            message: '长度在 1 到 15 个字符',
            trigger: 'blur'
          }
        ],
        berthLength: [
          {
            required: true,
            message: '请输入泊位长度',
            trigger: 'blur'
          }
        ],
        berthDeepth: [
          {
            required: true,
            message: '请输入泊位水深',
            trigger: 'blur'
          }
        ],
        companyId: [
          {
            required: true,
            message: '请输入所属公司',
            trigger: 'change'
          }
        ],
        isMain: [
          {
            required: true,
            message: '',
            trigger: 'change'
          }
        ],
        sortNum: [
          {
            required: true,
            message: '请输入排序号',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    addForm: {
      handler(newVal, oldVal) {
        // console.log(isObjectValueEqual(newVal, oldVal))
        this.flagHint = isObjectValueEqual(newVal, oldVal)
      },
      deep: true
    }
  },
  created() {
    // this.getBerthBaseData()
    // this.searchClick()
  },
  async activated() {
    var menuArr = []
    var menuId = ''
    if (localStorage.getItem('menuArr')) {
      menuArr = JSON.parse(localStorage.getItem('menuArr'))
    }
    menuArr.map(item => {
      item.children.map(v => {
        if (window.location.href.includes(v.url)) {
          menuId = v.id
        }
      })
    })

    if (menuId) {
      this.menuArr = []
      await publicapi.getPermissionsBtn(menuId)
        .then(res => {
          res.data.data.map(item => {
            this.menuArr.push(item.RESOURCENAME)
          })
          console.log(this.menuArr);

          if (!this.menuArr.includes('泊位新增')) {
            this.menuFlag = false
          } else {
            this.menuFlag = true
          }
        }).catch((error) => {})
    }
    if (this.$store.state.app.searchResouce == 'menu') {
      this.queryall = {
        startpage: 1,
        pagesize: 15
      };
      this.getCompanyList()
      this.getpreBerthIdList()
      this.getBerthBaseData()
      // this.searchClick()
    }
  },
  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight
    }
  },
  methods: {
    // 删除
    async del(index, row) {
      console.log(row)
      const confirmRes = await this.$confirm(
        '此操作将永久删除该数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {})
      if (confirmRes !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      this.deleteRecieptById(row.id)
      this.rowData = null
      this.outForm = null
    },
    // 删除
    async deleteRecieptById(id) {
      const res = await api.reqDeleteBerth(id)
      this.$notify.success({
        title: '温馨提示',
        message: '删除成功！'
      });
      this.searchClick()
    },
    // 过滤重量特殊符号
    setThree(val) {
      let num = val.replace(/[^\-?\d.]/g, '')
      const arr = num.split('')
      num = arr.filter((item, index) => {
        console.log(index)
        if (index != 0) {
          return item != '-'
        }
        return true
      }).join('')
      if (num.split('.')[1]) {
        return num.split('.')[0] + '.' + num.split('.')[1].substr(0, 3)
      }
      return num
    },
    setCount(val) {
      const num = val.replace(/[^\-?\d.]/g, '')
      if (num.split('.')[1]) {
        return num.split('.')[0]
      }
      return num.replace('.', '')
    },
    // 获取泊位下拉信息
    async getpreBerthIdList() {
      await publicapi.queryberthbytype('')
        .then(res => {
          this.preBerthIdList = res.data.data
          this.preBerthIdListMain = [];
          this.preBerthIdList.forEach(item => {
            if (item.isMain == 'Y') {
              this.preBerthIdListMain.push(item);
            }
          })
        }).catch(error => {});
    },
    // 获取select所属公司
    async getCompanyList() {
      await publicapi.getListComp()
        .then(res => {
          this.selectCompany = res.data.data;
          var selectCompanyTemp = [];
          this.selectCompany.map(item => {
            var obj = {};
            obj.dictLabel = item.companyName;
            obj.dictValue = item.companyId;
            selectCompanyTemp.push(obj)
          })
          this.selectObject[1].selectData = selectCompanyTemp;
        }).catch(error => {});
    },

    // 所属单位
    selectCompId() {
      this.addForm.companyName = ''
      this.selectCompany.forEach(n => {
        if (this.addForm.companyId === n.companyId) {
          this.addForm.companyName = n.companyName
        }
      })
    },
    // 所属区域
    selectRegionCode() {
      this.regionOption.forEach(n => {
        if (this.addForm.regionCode === n.dictValue) {
          this.addForm.regionName = n.dictLabel
        }
      })
    },
    handleCloseBefore(done) {
      if (this.flagHint) {
        this.$confirm('您已修改了数据，确定是否关闭？')
          .then(_ => {
            done()

            // this.$refs.addForm.resetFields()
          })
          .catch(_ => {})
      } else {
        done()
      }

      this.$refs.addForm.resetFields()
    },
    handleCloseBefore1(done) {
      done()
      this.queryInfo.bollardNo = ''
    },

    // 点击按钮,增加list
    addInfo() {
      this.berthLoading = false
      this.addDialogVisible = true
      this.flag = true
      this.flagHint = false
      this.addForm = {
        id: '',
        berthNo: '',
        berthNoMain: '',
        berthLength: '',
        berthDeepth: '',
        companyId: '',
        companyName: '',
        berthNoLeft: '',
        berthNoRight: '',
        isMain: 'Y',
        sortNum: '',
        delFlag: '0',
        regionCode: '',
        regionName: ''
      }
      this.$nextTick(() => {
        this.$refs.addForm.resetFields()
      })
    },
    // 打开列表
    excelFun(info) {
      this.nowData = info
      this.P_berthNo = info.berthNo

      this.exl = true
    },
    // 点击按钮，修改信息
    async handleEdit(index, info) {
      // DialogVisible显示
      this.berthLoading = false
      delete info.berthUseName
      this.addDialogVisible = true
      this.flag = false
      api.reqGetBerthById(info.id).then(res => {
        this.addForm = res.data.data
      })

      this.compId = info.companyId
    },

    // 每页显示的条数
    handleSizeChange(val) {
      this.queryall.pagesize = val
      this.getBerthInfoList()
    },
    // 当前页
    handleCurrentChange(val) {
      this.queryall.startpage = val
      this.getBerthInfoList()
    },

    // 添加泊位的函数
    addBerth() {
      delete this.addForm.createBy
      delete this.addForm.createName
      delete this.addForm.createTime
      delete this.addForm.updateBy
      delete this.addForm.updateName
      delete this.addForm.updateTime
      // delete this.addForm.delFlag
      // delete this.addForm.companyName
      // this.addForm.companyId = this.compId
      this.$refs['addForm'].validate(async valid => {
        if (valid) {
          this.berthLoading = true
          if (this.flag) {
            // 新增
            // 应该是必填字段的问题(请注意)
            await api
              .reqPostAddBerth(this.addForm)
              .then(res => {
                this.addDialogVisible = false
                this.$message.success(res.data.msg)
                this.getBerthInfoList()
                this.berthLoading = false
              }).catch(error => { this.berthLoading = false })
          } else {
            // 编辑
            /* delete this.addForm.berthUseName
            delete this.addForm.mbittList
            delete this.addForm.berthLevelName
            delete this.addForm.berthNatureName*/
            await api
              .reqPutUpdateBerth(this.addForm)
              .then(res => {
                this.addDialogVisible = false
                this.$message.success(res.data.msg)
                this.getBerthInfoList()
                this.berthLoading = false
              }).catch(error => { this.berthLoading = false })
          }
        } else {
          return false
        }
      })
    },
    searchClick(searchData) {
      this.queryall.startpage = 1
      this.form = Object.assign(this.form, searchData);
      this.getBerthInfoList()
    },
    // 获取table信息
    async getBerthInfoList() {
      this.loading = true
      this.form = Object.assign(this.form, this.queryall);
      await api
        .reqGetBerth(this.form)
        .then(res => {
          this.cargotableData = res.data.data.pages
          this.queryall.startpage = res.data.data.pageNum
          this.queryall.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
          this.loading = false
        }).catch(error => {})
    },
    // 获取泊位性质、设计船型基础信息 从字典值取
    getBerthBaseData() {
      publicapi.getDictData('REGION')
        .then(res => {
          this.regionOption = res.data.data.REGION
        })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.vue-treeselect__control {
  height: 28px !important;
}
/deep/.vue-treeselect__placeholder,
/deep/.vue-treeselect__single-value {
  line-height: 28px !important;
  font-size: 12px !important;
}

.lanzhuang /deep/ .el-drawer__open .el-drawer.rtl {
  width: 50% !important;
}
.form-t {
  margin-bottom: 50px;
  padding: 0 1rem;
}
.form-t /deep/ .el-form-item__content {
  margin-left: 1rem !important;
  width: 60%;
  float:right;
}
/deep/ .el-button--primary {
  background-color: #338ce8;
  border-color: #338ce8;
}
// /deep/ .el-form-item {
//   display: flex;
// }
.page {
  background: #ffffff;
  margin-top: 4px;
  border-radius: 4px 4px 0 0;
  line-height: 35px;
  padding-right: 1rem;
}
.box {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-top: none !important;
  border-radius: 4px 4px 0 0;
}
.title {
  background: #f5f7fa;
  height: 40px;
  line-height: 40px;
  p {
    font-family: MicrosoftYaHei;
    font-size: 16px;
    color: #303133;
    letter-spacing: 0;
    line-height: 16px;
    padding-left: 14px;
    line-height: 40px;
  }
}

/deep/ .el-table .cell {
  white-space: nowrap;
}
/deep/ .el-form-item--mini .el-form-item__label {
  line-height: 0;
}
/deep/ .el-pagination {
  text-align: right;
}
/deep/ .el-table th > .cell {
  font-family: PingFangSC-Semibold;
  font-size: 14px;
  color: #606266;
}
/deep/ .el-drawer__header {
  margin-bottom: 0;
  // padding: 8px 16px;
  border-bottom: 1px solid gainsboro;
}
/deep/ .el-drawer__body {
  overflow-y: auto;
}
/deep/ .el-table .el-button:focus,
.el-button:hover {
  background-color: #fff;
  color: #338ce8;
  border: 1px solid #e1e4eb;
}
/deep/ .v-modal {
  z-index: 200 !important;
}
/deep/ .el-table .el-button--mini {
  color: #1684f6;
  border-color: transparent;
  background: transparent;
}
/deep/ .el-table th {
  border-left: 1px solid #ebeef5;
}
/deep/ .el-table th:nth-child(1) {
  border-left: none;
}
/deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f5f7fa;
}
/deep/.el-pagination.is-background .btn-next,
/deep/ .el-pagination.is-background .btn-prev,
/deep/ .el-pagination.is-background .el-pager li {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 3px;
  border-radius: 3px;
}

/deep/ .el-drawer__header {
  padding: 10px;
}
.selectBox {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-bottom: 0;
  border-left: none;
  line-height: 28px;
  height: 50px;
  position: relative;
  display: flex;
  align-items: center;
  padding-left: 16px;
  padding-right: 16px;
}
/deep/ .el-button + .el-button {
  margin-left: 3px;
}
</style>
